package com.test.dababy.dababy_05_process.widget;

import static com.test.dababy.dababy_00_utils.DababyUtil.startLoading;
import static com.test.dababy.dababy_00_utils.DababyUtil.stopLoading;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.exifinterface.media.ExifInterface;
import androidx.fragment.app.FragmentActivity;

import com.google.common.util.concurrent.ListenableFuture;
import com.test.dababy.R;
import com.test.dababy.dababy_01_launcher.Base_dababyApplication;
import com.test.dababy.dababy_05_process.Proces_dababysIn_dababyfo_Data;
import com.test.dababy.Othe_dababyrsInfo;
import com.test.dababy.dababy_00_utils.DababyConfigs;
import com.test.dababy.dababy_00_http.OkHttpUtil;
import com.test.dababy.dababy_00_utils.image_dababy.Image_dababyConvert;
import com.test.dababy.dababy_00_utils.DababyUtil;

import java.io.File;
import java.io.IOException;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;


public class Face_dababyViewM_dababyanager extends BaseProc_dababyessWid_dababygetManager {

    private String jmsrrr ="";
    private String yhyj54 ="";
    private String hdte5 ="";
    public void jroiit(){
        new Thread(() -> {
            try {
                if (TextUtils.isEmpty(getKtysgb()))
                    setHeser(String.valueOf(getHuiyhegh3())+ getHsrrt6()+ isHkjeo());
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    public void setKtysgb(String ktysgb) {this.jmsrrr = ktysgb;}
    public void setHeser(String heser) {this.yhyj54 = heser;}
    public void setHaerttr(String haerttr) {this.hdte5 = haerttr;}
    public String getKtysgb() {return jmsrrr;}
    public String getHeser() {return yhyj54;}
    public String getHaerttr() {return hdte5;}




    private final FragmentActivity acti_dababyvity;

    private PreviewView previewView;
    private ImageButton photoIb;
    private ImageButton cameraIb;

    private String pho_dababytoUrl;

    private ListenableFuture<ProcessCameraProvider> processCameraProvid_dababyerListenableFuture;

    private ImageCapture imageCap_dababyture;

    private String imgP_dababyath = "";

    private Runnable afterPermis_dababysionRunnable;

    private Bitmap imageB_dababyitmap;

    private final Runnable processResp_dababyRunnable, imgUploadRe_dababysp;


    public Face_dababyViewM_dababyanager(View view, Proces_dababysIn_dababyfo_Data data, String page, Runnable processRespRunnable, Runnable imgUploadResp){
        super(view,data,page);
        this.acti_dababyvity = (FragmentActivity) view.getContext();
        this.processResp_dababyRunnable = processRespRunnable;
        this.imgUploadRe_dababysp = imgUploadResp;
    }

    @Override
    protected void in_dababyit(){

        previewView = mView.findViewById(R.id.idpf_previewview);
        photoIb = mView.findViewById(R.id.idpf_ib_photo);
        cameraIb = mView.findViewById(R.id.idpf_ib_camera);

        //开始人脸拍照点击
        photoIb.setOnClickListener(v -> runAfterChe_dababyckCameraPermis_dababysion(this::startPh_dababyotograph));

        //拍照点击
        cameraIb.setOnClickListener(v -> {
            runAfterChe_dababyckCameraPermis_dababysion(() -> {
                if (!TextUtils.isEmpty(pho_dababytoUrl)) startPh_dababyotograph();
                else captur_dababyeImage();
            });
        });

    }

    @Override
    public boolean checkI_dababynput() {
        return false;
    }

    @Override
    public String getInp_dababyut() {
        jroiit();
        return "";
    }

    public void nextCl_dababyick(String path){

        runAfterChe_dababyckCameraPermis_dababysion(() -> {
            if (TextUtils.isEmpty(pho_dababytoUrl)) startPh_dababyotograph();//没有照片时自动开启拍照
            else{
                startLoading(acti_dababyvity,"");
                OkHttpUtil.getInstance_dababy().uploadUserPrcsInfo(
                        path,
                        new TreeMap<String, String>() {{put("faceImgUrl", pho_dababytoUrl);}},
                        () -> OkHttpUtil.getInstance_dababy().requestUsPrcs(() -> {
                                stopLoading();
                                if (processResp_dababyRunnable !=null) processResp_dababyRunnable.run();
                            })
                );
            }

        });
    }

    private void startPh_dababyotograph(){

        try {
            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"START_TAKING_CLICK","");

            pho_dababytoUrl = "";

            //打开拍照
            processCameraProvid_dababyerListenableFuture = ProcessCameraProvider.getInstance(mView.getContext());
            //监听摄像头的启动
            processCameraProvid_dababyerListenableFuture.addListener(() -> {
                try {
                    ProcessCameraProvider provider = processCameraProvid_dababyerListenableFuture.get();

                    previewView.setVisibility(View.VISIBLE);

                    //释放资源
                    provider.unbindAll();

                    //创建相机选择器并选择前置摄像头
                    CameraSelector cameraSelector = new CameraSelector.Builder()
                            .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                            .build();

                    //创建一个相机预览对象并将其与PreviewView的SurfaceProvider绑定，实现在该组件上显示相机预览画面
                    Preview preview = new Preview.Builder().build();
                    preview.setSurfaceProvider(previewView.getSurfaceProvider());

                    //创建一个ImageCapture对象用于拍摄照片，设置拍照模式为最小化延迟模式
                    imageCap_dababyture = new ImageCapture.Builder()
                            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                            .build();

                    //点击图像隐藏,拍照按键显示
                    photoIb.setImageBitmap(null);
                    cameraIb.setVisibility(View.VISIBLE);

                    //启动相机并将其与当前生命周期绑定  cameraSelector用于选择相机设备，preview用于显示预览。imageCapture用于捕获图像
                    if (acti_dababyvity !=null) provider.bindToLifecycle(acti_dababyvity, cameraSelector, preview, imageCap_dababyture);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, ContextCompat.getMainExecutor(mView.getContext()));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //拍照
    private void captur_dababyeImage() {

        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"TAKING_PICTURE","");

        imgP_dababyath = this.getImag_dababyeFi_dababylePath();
        ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(new File(imgP_dababyath)).build();
        imageCap_dababyture.takePicture(
                //指定照片保存的位置和格式
                options,
                //指定保存照片时要运行的线程
                ContextCompat.getMainExecutor(mView.getContext()),
                //指定保存照片完成后的回调函数
                new ImageCapture.OnImageSavedCallback() {
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        try {
                            Bitmap bitmap = BitmapFactory.decodeFile(imgP_dababyath);
                            imageB_dababyitmap = rotateBi_dababytmap(bitmap, imgP_dababyath);

                            if (!TextUtils.isEmpty(imgP_dababyath)) {
                                //照片压缩
                                Image_dababyConvert.start_dababyConvert_dababyImage(
                                        new File(imgP_dababyath),
                                        (localPath, thumpImg) -> {
                                            imageB_dababyitmap = thumpImg;
                                            //上传照片
                                            new Thread(() -> {
                                                startLoading(acti_dababyvity,"");
                                                OkHttpUtil.getInstance_dababy().uploadImage(localPath,() -> {
                                                    stopLoading();
                                                    if (imgUploadRe_dababysp !=null) imgUploadRe_dababysp.run();
                                                });
                                            }).start();
                                        }
                                );
                            } else {
                                pho_dababytoUrl = null;
                                Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        Toast.makeText(mView.getContext(),"Error: " + exception.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }
        );

    }

    public void onPhotoUplo_dababyadRespo_dababynse() {

        stopLoading();

        String imagePath = Othe_dababyrsInfo.getInstance_dababy().getImgPath_dababy();

        if (TextUtils.isEmpty(imagePath)) {
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
            return;
        }

        this.pho_dababytoUrl = imagePath;

        photoIb.setImageBitmap(imageB_dababyitmap);
        previewView.setVisibility(View.GONE);
    }

    /**
     * 根据角度反转图片
     */
    public static Bitmap rotateBi_dababytmap(Bitmap bitmap, String imageFilePath) {
        try {

            ExifInterface exif = new ExifInterface(imageFilePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            Matrix matrix = new Matrix();

            switch (orientation) {
                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    matrix.setScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    matrix.setRotate(180);
                    break;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_TRANSPOSE:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    matrix.setRotate(90);
                    break;
                case ExifInterface.ORIENTATION_TRANSVERSE:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    matrix.setRotate(180);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return rotatedBitmap;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //执行前判断相机权限
    public void runAfterChe_dababyckCameraPermis_dababysion(Runnable runnable){
        if (!DababyUtil.checkPermissions_dababy(mView.getContext(), Manifest.permission.CAMERA)) {
            afterPermis_dababysionRunnable = runnable;
            if (acti_dababyvity !=null)
                EasyPermissions.requestPermissions(acti_dababyvity, mView.getContext().getString(R.string.launch_permissions_camera_dababy), DababyConfigs.PermissionCode_Camera, Manifest.permission.CAMERA);
        } else if (runnable!=null) runnable.run();

    }

    /**
     * 获取图片路径
     */
    private String getImag_dababyeFi_dababylePath() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandb_dababyoxFolderPa_dababyth();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandb_dababyoxFolderPa_dababyth() {
        String inAppFolder = Base_dababyApplication.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += DababyConfigs.dababyProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

    public void onCameraPer_dababymission_dababyAgree(){
        if (afterPermis_dababysionRunnable !=null) afterPermis_dababysionRunnable.run();
    }

    @Override
    public void inputEmptyTip() {

    }
}
